const state = {
  // 购物车的数组，用来存储购物车中商品的信息
  cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
}
const actions = {

}

const mutations = {
  ADDTOCART(state, goods) {
    const res = state.cart.find(x => x.goods_id == goods.goods_id);
    if (res === undefined) {
      state.cart.push(goods)
    } else {
      res.goods_count++;
    }
    this.commit('cart/SAVETOSTORAGE');
  },
  SAVETOSTORAGE(state) {
    uni.setStorageSync('cart', JSON.stringify(state.cart))
  },
  IPDATEGOODSSTATE(state, goods) {
    const res = state.cart.find(x => x.goods_id == goods.goods_id)
    if (res) {
      res.goods_state = goods.goods_state;
      this.commit('cart/SAVETOSTORAGE');
    }
  },
  UPDATEGOODSCOUNT(state, goods) {
    const res = state.cart.find(x => x.goods_id == goods.goods_id)
    if (res) {
      res.goods_count = goods.goods_count;
      this.commit('cart/SAVETOSTORAGE');
    }
  },
  REMOVEGOODSBYID(state, id) {
    state.cart = state.cart.filter(x => x.goods_id !== id);
    this.commit('cart/SAVETOSTORAGE');
  },
  ALLCHECKED(state, boolean) {
    state.cart.forEach(item => {
      item.goods_state = boolean
    })
  }
}

const getters = {
  cartSUM(state) {
    return state.cart.reduce((before, cur) => {
      return before + (cur.goods_count - 0);
    }, 0)
  },
  checkedSum(state) {
    // let count=0;
    // state.cart.forEach(item=>{
    //   count+=item.goods_state?1:0
    // })
    // return count;
    return state.cart.reduce((before, cur, index) => {
      return before + (cur.goods_state ? 1 : 0)*cur.goods_count;
    }, 0)
  },
  priceSum(state) {
    return state.cart.reduce((before, cur) => {
      return before + cur.goods_count * cur.goods_price*cur.goods_state;
    }, 0)
  },
  checkAll(state) {
    for (let item of state.cart) {
      if (item.goods_state === false) {
        return false
      }
    }
    return true;
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}
